var snake;
//储存蛇的位置，长度等信息
var date;
//储存得分，时间等信息
var food;
//储存食物信息
var timer = null;
//计时器

var end,start;
//计算游戏时长的工具

const  button1 = document.getElementById('button1'),
       button2 = document.getElementById('button2'),
       button3 = document.getElementById('button3');
//设置游戏难度
const mingrid = 16;
//像素点大小

function getrandomint(max,min){
    return (Math.floor(Math.random()*(max-min))+min)*mingrid;
}//生成随机数

function startgame(){//开始游戏
    start = new Date();//记录游戏开始的时间
    snake = {
        x: 160,
        y: 160,
        //蛇初始位置
        dx: mingrid,
        dy: 0,
        //初始速度
        len: 4,
        //初始长度
        cells: []
        //蛇的结点
    }
    date = {
        score: 0,
        //游戏得分
        time: 0,
        //游戏时长
        speed: 300
        //刷新速度
    }
    food = {
        x: getrandomint(0,25),
        y: getrandomint(0,25)
        //随机生成食物
    }

    if (timer == null){
        timer = setInterval(loop, date.speed)
        //计时开始
    }
}

function endgame(){
    clearInterval(timer);
    timer = null;
    //计时结束
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.font = "50px Arial";
    context.textAlign = "center";
    context.fillStyle = 'blue';
    context.fillText("GAME OVER", canvas.width / 2, canvas.height / 3);
     // 显示 GAME OVER
    context.font = "30px Arial";
    context.fillText("Your score:"+String(date.score)+"   Time:"+String(Math.ceil(date.time)), canvas.width / 2, canvas.height / 2)
    context.fillText("Enter for new game.", canvas.width / 2, canvas.height / 1.5)
    //显示得分等数据
}

function loop(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    end = new Date();
    //记录现在时间
    date.time =(end.getTime() - start.getTime())/1000;
    //计算游戏时长
    document.getElementById('time').innerText = Math.ceil(date.time);
    //显示游戏时长
    snake.x += snake.dx;
    snake.y += snake.dy;
    //移动蛇头
    snake.cells.unshift({
        x: snake.x,
        y: snake.y
    });
    //将新蛇头添加进蛇结点中
    if (snake.cells.length > snake.len) {
        snake.cells.pop();
    }
    // 判断蛇吃到食物
    if (snake.x === food.x && snake.y === food.y) {
        // 生长
        snake.len += 1; //每次长1个节点
        if (date.speed == 50) date.score += 3;
        else if (date.speed == 150) date.score += 2;
        else date.score += 1;
        //根据速度增加得分
        document.getElementById('score').innerText = date.score;
        //显示得分
        food.x = getrandomint(0,25),
        food.y = getrandomint(0,25)
        // 生成新的食物
    }    

    // 判断是否撞墙
    if (snake.x < 0 || snake.x >= canvas.width || snake.y < 0 || snake.y >= canvas.height) {
        endgame();
        return;
    }

    // 判断是否有和自己碰撞的情况
    for (var i = 1; i < snake.cells.length; i++) {
        if (snake.cells[i].x === snake.x && snake.cells[i].y === snake.y) {
            endgame();
            return;
        }
    }

    // 绘制食物
    context.fillStyle = 'red';
    context.fillRect(food.x, food.y, mingrid - 1, mingrid - 1);

    // 绘制蛇
    context.fillStyle = 'green';
    // 画每一个节点，节点间有1个像素的间隙
    for (var i = 0; i < snake.cells.length; i++) {
        context.fillRect(snake.cells[i].x, snake.cells[i].y, mingrid - 1, mingrid - 1);
    };    
}

// 处理键盘按键
function onKeyDown(keyEvent) {

    // enter键，重启游戏。
    if (keyEvent.key == "Enter") {
        startgame()
    }
    // 上下左右键，改变蛇的方向，但不能掉头
    // left arrow key
    else if (keyEvent.key == "ArrowLeft" && snake.dx == 0) {
        snake.dx = -mingrid;
        snake.dy = 0;
    }
    // up arrow key
    else if (keyEvent.key == "ArrowUp" && snake.dy == 0) {
        snake.dy = -mingrid;
        snake.dx = 0;
    }
    // right arrow key
    else if (keyEvent.key == "ArrowRight" && snake.dx == 0) {
        snake.dx = mingrid;
        snake.dy = 0;
    }
    // down arrow key
    else if (keyEvent.key == "ArrowDown" && snake.dy == 0) {
        snake.dy = mingrid;
        snake.dx = 0;
    }
}

var canvas = document.getElementById('game');
var context = canvas.getContext('2d');

document.addEventListener('keydown', onKeyDown);
// 设置键盘监听

button1.addEventListener('click',() => {
    date.speed = 300;
    clearInterval(timer);
    timer = setInterval(loop, date.speed)
})
button2.addEventListener('click',() => {
    date.speed = 150;
    clearInterval(timer);
    timer = setInterval(loop, date.speed)
})
button3.addEventListener('click',() => {
    date.speed = 50;
    clearInterval(timer);
    timer = setInterval(loop, date.speed)
})
//设置按键监听

startgame();
// 游戏开始